//
//  WDKeychainInfoManager.m
//  WDGroMore
//
//  Created by little People on 2023/7/26.
//

#import "WDKeychainInfoManager.h"

@implementation WDKeychainInfoManager
static WDKeychainInfoManager *_manager = nil;
static NSString *keychainService  = @"GroMoreKeychainService";
static NSString *keychainUUID     = @"GroMoreKeychainUUID";

+ (instancetype)manager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}

- (NSMutableDictionary *)getKeychainQuery:(NSString *)service accountId:(NSString *)accountId {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (id)kSecClassGenericPassword,(id)kSecClass,//类型
            service, (id)kSecAttrService,//服务
            accountId, (id)kSecAttrAccount,//帐户
            (id)kSecAttrAccessibleAlwaysThisDeviceOnly,(id)kSecAttrAccessible,//访问的类型
            nil];
}

- (NSString *)WDKeychainGetUUID
{
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:keychainService accountId:keychainUUID];
    //查询的返回类型
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    //返回的数目
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", keychainService, e);
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    if (ret)
    {
        return ret;
    }else{
        NSString *uuid = [[NSUUID UUID] UUIDString];
        [self WDKeychainSaveUUID:uuid];
        return uuid;
    }
    return ret;
}

- (void)WDKeychainSaveUUID:(NSString *)uuid
{
    //创建查询支点
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:keychainService accountId:keychainUUID];
    //创建新的 item 前先删除旧的 item
    SecItemDelete((CFDictionaryRef)keychainQuery);
    //先把需要存储的数据序列化，
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:uuid] forKey:(id)kSecValueData];
    //创建新的 item 到keychain
    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}
@end
